package cn.util;

import cn.entity.AccessToken;
import com.alibaba.fastjson.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Wechat {

    private static AccessToken accessToken;

    public static JSONObject getAccess_token(String appId, String appSecret) {
        String url = WeChatMpInterface.WX_TOKEN + appId + "&secret=" + appSecret;
        String token = null;
        JSONObject jsonObj = null;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            token = new String(jsonBytes, "UTF-8");
            System.err.println(token);
            jsonObj = JSONObject.parseObject(token);
            accessToken = new AccessToken();
            accessToken.setAccess_token(jsonObj.getString("access_token"));
            accessToken.setExpiresTime(jsonObj.getLong("expires_in"));
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObj;
    }

    public static AccessToken getToken(String appId, String appSecret){
        if (accessToken == null || accessToken.isExpired()){
            return JSONObject.parseObject(getAccess_token(appId, appSecret).toString(), AccessToken.class);

        }
        return accessToken;
    }

}
